package com.okilo.online.app.weight

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import android.widget.LinearLayout
import com.okilo.online.app.R
import androidx.core.graphics.toColorInt
import androidx.core.content.withStyledAttributes


/**
 * 指示气泡ViewGroup
 */
class BubbleLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    private val bubblePaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val fillPath = Path()
    private val borderPath = Path()

    // 气泡属性
    private var bubbleColor = Color.WHITE
    private var borderColor = "#DDDDDD".toColorInt()
    private var borderWidth = 2f
    private var cornerRadius = 16f
    private var triangleWidth = 24f
    private var triangleHeight = 12f
    private var trianglePosition = TRIANGLE_POSITION_BOTTOM

    companion object {
        const val TRIANGLE_POSITION_TOP = 0
        const val TRIANGLE_POSITION_BOTTOM = 1
        const val TRIANGLE_POSITION_LEFT = 2
        const val TRIANGLE_POSITION_RIGHT = 3
    }

    // 内容区域边距（为三角形预留空间）
    private val contentPadding = intArrayOf(0, 0, 0, 0)

    init {
        setupAttributes(attrs)
        setupPaints()
        updateContentPadding()
        setWillNotDraw(false)
    }

    private fun setupAttributes(attrs: AttributeSet?) {
        attrs?.let {
            context.withStyledAttributes(it, R.styleable.BubbleLayout) {

                bubbleColor = getColor(
                    R.styleable.BubbleLayout_bubbleColor,
                    Color.WHITE
                )

                borderColor = getColor(
                    R.styleable.BubbleLayout_borderColor,
                    "#DDDDDD".toColorInt()
                )

                borderWidth = getDimension(
                    R.styleable.BubbleLayout_borderWidth,
                    2f
                )

                cornerRadius = getDimension(
                    R.styleable.BubbleLayout_cornerRadius,
                    16f
                )

                triangleWidth = getDimension(
                    R.styleable.BubbleLayout_triangleWidth,
                    24f
                )

                triangleHeight = getDimension(
                    R.styleable.BubbleLayout_triangleHeight,
                    12f
                )

                trianglePosition = getInt(
                    R.styleable.BubbleLayout_trianglePosition,
                    TRIANGLE_POSITION_BOTTOM
                )

            }
        }
    }

    private fun setupPaints() {
        bubblePaint.style = Paint.Style.FILL
        bubblePaint.color = bubbleColor

        borderPaint.style = Paint.Style.STROKE
        borderPaint.color = borderColor
        borderPaint.strokeWidth = borderWidth
        borderPaint.strokeJoin = Paint.Join.ROUND
    }

    private fun updateContentPadding() {
        when (trianglePosition) {
            TRIANGLE_POSITION_TOP -> {
                contentPadding[0] = paddingLeft
                contentPadding[1] = paddingTop + triangleHeight.toInt()
                contentPadding[2] = paddingRight
                contentPadding[3] = paddingBottom
            }
            TRIANGLE_POSITION_BOTTOM -> {
                contentPadding[0] = paddingLeft
                contentPadding[1] = paddingTop
                contentPadding[2] = paddingRight
                contentPadding[3] = paddingBottom + triangleHeight.toInt()
            }
            TRIANGLE_POSITION_LEFT -> {
                contentPadding[0] = paddingLeft + triangleHeight.toInt()
                contentPadding[1] = paddingTop
                contentPadding[2] = paddingRight
                contentPadding[3] = paddingBottom
            }
            TRIANGLE_POSITION_RIGHT -> {
                contentPadding[0] = paddingLeft
                contentPadding[1] = paddingTop
                contentPadding[2] = paddingRight + triangleHeight.toInt()
                contentPadding[3] = paddingBottom
            }
        }

        super.setPadding(
            contentPadding[0],
            contentPadding[1],
            contentPadding[2],
            contentPadding[3]
        )
    }

    override fun onDraw(canvas: Canvas) {
        drawBubbleBackground(canvas)
        super.onDraw(canvas)
    }

    override fun dispatchDraw(canvas: Canvas) {
        drawBubbleBackground(canvas)
        super.dispatchDraw(canvas)
    }

    private fun drawBubbleBackground(canvas: Canvas) {
        fillPath.reset()
        borderPath.reset()

        // 创建完整的气泡路径（矩形 + 三角形）
        createBubblePath()

        // 先绘制填充
        canvas.drawPath(fillPath, bubblePaint)

        // 再绘制边框
        if (borderWidth > 0) {
            canvas.drawPath(borderPath, borderPaint)
        }
    }

    private fun createBubblePath() {
        val halfBorder = borderWidth / 2

        when (trianglePosition) {
            TRIANGLE_POSITION_BOTTOM -> createBottomBubblePath(halfBorder)
            TRIANGLE_POSITION_TOP -> createTopBubblePath(halfBorder)
            TRIANGLE_POSITION_LEFT -> createLeftBubblePath(halfBorder)
            TRIANGLE_POSITION_RIGHT -> createRightBubblePath(halfBorder)
        }
    }

    private fun createBottomBubblePath(halfBorder: Float) {
        val contentWidth = width.toFloat()
        val contentHeight = height.toFloat() - triangleHeight

        // 填充路径：完整的圆角矩形 + 三角形
        val fillRect = RectF(0f, 0f, contentWidth, contentHeight)
        fillPath.addRoundRect(fillRect, cornerRadius, cornerRadius, Path.Direction.CW)

        val triangleStartX = (contentWidth - triangleWidth) / 2
        val triangleEndX = triangleStartX + triangleWidth
        val triangleTop = contentHeight
        val triangleBottom = contentHeight + triangleHeight

        fillPath.moveTo(triangleStartX, triangleTop)
        fillPath.lineTo(triangleEndX, triangleTop)
        fillPath.lineTo(contentWidth / 2, triangleBottom)
        fillPath.close()

        // 边框路径：完整的轮廓路径
        borderPath.moveTo(halfBorder + cornerRadius, halfBorder)

        // 顶部边框
        borderPath.lineTo(contentWidth - cornerRadius - halfBorder, halfBorder)
        borderPath.arcTo(
            RectF(
                contentWidth - cornerRadius * 2 - halfBorder,
                halfBorder,
                contentWidth - halfBorder,
                cornerRadius * 2 + halfBorder
            ),
            -90f,
            90f,
            false
        )

        // 右侧边框
        borderPath.lineTo(contentWidth - halfBorder, contentHeight - cornerRadius - halfBorder)
        borderPath.arcTo(
            RectF(
                contentWidth - cornerRadius * 2 - halfBorder,
                contentHeight - cornerRadius * 2 - halfBorder,
                contentWidth - halfBorder,
                contentHeight - halfBorder
            ),
            0f,
            90f,
            false
        )

        // 底部右侧边框（到三角形起点）
        borderPath.lineTo(triangleEndX - halfBorder, contentHeight - halfBorder)

        // 三角形右侧边框
        borderPath.lineTo(contentWidth / 2, triangleBottom - halfBorder)

        // 三角形左侧边框
        borderPath.lineTo(triangleStartX + halfBorder, contentHeight - halfBorder)

        // 底部左侧边框
        borderPath.lineTo(cornerRadius + halfBorder, contentHeight - halfBorder)
        borderPath.arcTo(
            RectF(
                halfBorder,
                contentHeight - cornerRadius * 2 - halfBorder,
                cornerRadius * 2 + halfBorder,
                contentHeight - halfBorder
            ),
            90f,
            90f,
            false
        )

        // 左侧边框
        borderPath.lineTo(halfBorder, cornerRadius + halfBorder)
        borderPath.arcTo(
            RectF(
                halfBorder,
                halfBorder,
                cornerRadius * 2 + halfBorder,
                cornerRadius * 2 + halfBorder
            ),
            180f,
            90f,
            false
        )

        borderPath.close()
    }

    private fun createTopBubblePath(halfBorder: Float) {
        val contentWidth = width.toFloat()
        val contentHeight = height.toFloat() - triangleHeight

        // 填充路径
        val fillRect = RectF(0f, triangleHeight, contentWidth, height.toFloat())
        fillPath.addRoundRect(fillRect, cornerRadius, cornerRadius, Path.Direction.CW)

        val triangleStartX = (contentWidth - triangleWidth) / 2
        val triangleEndX = triangleStartX + triangleWidth
        val triangleTop = triangleHeight
        val triangleBottom = 0f

        fillPath.moveTo(triangleStartX, triangleTop)
        fillPath.lineTo(triangleEndX, triangleTop)
        fillPath.lineTo(contentWidth / 2, triangleBottom)
        fillPath.close()

        // 边框路径
        borderPath.moveTo(contentWidth / 2, triangleBottom + halfBorder)
        borderPath.lineTo(triangleEndX - halfBorder, triangleTop + halfBorder)
        borderPath.lineTo(contentWidth - cornerRadius - halfBorder, triangleTop + halfBorder)

        // 顶部右侧边框
        borderPath.arcTo(
            RectF(
                contentWidth - cornerRadius * 2 - halfBorder,
                triangleTop + halfBorder,
                contentWidth - halfBorder,
                triangleTop + cornerRadius * 2 + halfBorder
            ),
            -90f,
            90f,
            false
        )

        // 右侧边框
        borderPath.lineTo(contentWidth - halfBorder, height - cornerRadius - halfBorder)
        borderPath.arcTo(
            RectF(
                contentWidth - cornerRadius * 2 - halfBorder,
                height - cornerRadius * 2 - halfBorder,
                contentWidth - halfBorder,
                height - halfBorder
            ),
            0f,
            90f,
            false
        )

        // 底部边框
        borderPath.lineTo(cornerRadius + halfBorder, height - halfBorder)
        borderPath.arcTo(
            RectF(
                halfBorder,
                height - cornerRadius * 2 - halfBorder,
                cornerRadius * 2 + halfBorder,
                height - halfBorder
            ),
            90f,
            90f,
            false
        )

        // 左侧边框
        borderPath.lineTo(halfBorder, triangleTop + cornerRadius + halfBorder)
        borderPath.arcTo(
            RectF(
                halfBorder,
                triangleTop + halfBorder,
                cornerRadius * 2 + halfBorder,
                triangleTop + cornerRadius * 2 + halfBorder
            ),
            180f,
            90f,
            false
        )

        // 顶部左侧边框
        borderPath.lineTo(triangleStartX + halfBorder, triangleTop + halfBorder)
        borderPath.lineTo(contentWidth / 2, triangleBottom + halfBorder)

        borderPath.close()
    }

    private fun createLeftBubblePath(halfBorder: Float) {
        val contentWidth = width.toFloat() - triangleHeight
        val contentHeight = height.toFloat()

        // 填充路径
        val fillRect = RectF(triangleHeight, 0f, width.toFloat(), contentHeight)
        fillPath.addRoundRect(fillRect, cornerRadius, cornerRadius, Path.Direction.CW)

        val triangleStartY = (contentHeight - triangleWidth) / 2
        val triangleEndY = triangleStartY + triangleWidth
        val triangleLeft = triangleHeight
        val triangleRight = 0f

        fillPath.moveTo(triangleLeft, triangleStartY)
        fillPath.lineTo(triangleLeft, triangleEndY)
        fillPath.lineTo(triangleRight, contentHeight / 2)
        fillPath.close()

        // 修复边框路径
        borderPath.moveTo(triangleRight + halfBorder, contentHeight / 2)
        borderPath.lineTo(triangleLeft + halfBorder, triangleStartY + halfBorder)

        // 顶部左侧边框（从三角形到圆角）
        borderPath.lineTo(triangleLeft + halfBorder, cornerRadius + halfBorder)
        borderPath.arcTo(
            RectF(
                triangleLeft + halfBorder,
                halfBorder,
                triangleLeft + cornerRadius * 2 + halfBorder,
                cornerRadius * 2 + halfBorder
            ),
            180f,
            90f,
            false
        )

        // 顶部边框
        borderPath.lineTo(width - cornerRadius - halfBorder, halfBorder)
        borderPath.arcTo(
            RectF(
                width - cornerRadius * 2 - halfBorder,
                halfBorder,
                width - halfBorder,
                cornerRadius * 2 + halfBorder
            ),
            -90f,
            90f,
            false
        )

        // 右侧边框
        borderPath.lineTo(width - halfBorder, contentHeight - cornerRadius - halfBorder)
        borderPath.arcTo(
            RectF(
                width - cornerRadius * 2 - halfBorder,
                contentHeight - cornerRadius * 2 - halfBorder,
                width - halfBorder,
                contentHeight - halfBorder
            ),
            0f,
            90f,
            false
        )

        // 底部边框
        borderPath.lineTo(triangleLeft + cornerRadius + halfBorder, contentHeight - halfBorder)
        borderPath.arcTo(
            RectF(
                triangleLeft + halfBorder,
                contentHeight - cornerRadius * 2 - halfBorder,
                triangleLeft + cornerRadius * 2 + halfBorder,
                contentHeight - halfBorder
            ),
            90f,
            90f,
            false
        )

        // 左侧底部边框（从圆角到三角形）
        borderPath.lineTo(triangleLeft + halfBorder, triangleEndY - halfBorder)
        borderPath.lineTo(triangleRight + halfBorder, contentHeight / 2)

        borderPath.close()
    }

    private fun createRightBubblePath(halfBorder: Float) {
        val contentWidth = width.toFloat() - triangleHeight
        val contentHeight = height.toFloat()

        // 填充路径
        val fillRect = RectF(0f, 0f, contentWidth, contentHeight)
        fillPath.addRoundRect(fillRect, cornerRadius, cornerRadius, Path.Direction.CW)

        val triangleStartY = (contentHeight - triangleWidth) / 2
        val triangleEndY = triangleStartY + triangleWidth
        val triangleLeft = contentWidth
        val triangleRight = contentWidth + triangleHeight

        fillPath.moveTo(triangleLeft, triangleStartY)
        fillPath.lineTo(triangleLeft, triangleEndY)
        fillPath.lineTo(triangleRight, contentHeight / 2)
        fillPath.close()

        // 边框路径
        borderPath.moveTo(triangleRight - halfBorder, contentHeight / 2)
        borderPath.lineTo(triangleLeft - halfBorder, triangleEndY - halfBorder)
        borderPath.lineTo(triangleLeft - halfBorder, contentHeight - cornerRadius - halfBorder)

        // 底部右侧边框
        borderPath.arcTo(
            RectF(
                contentWidth - cornerRadius * 2 - halfBorder,
                contentHeight - cornerRadius * 2 - halfBorder,
                contentWidth - halfBorder,
                contentHeight - halfBorder
            ),
            0f,
            90f,
            false
        )

        // 底部边框
        borderPath.lineTo(cornerRadius + halfBorder, contentHeight - halfBorder)
        borderPath.arcTo(
            RectF(
                halfBorder,
                contentHeight - cornerRadius * 2 - halfBorder,
                cornerRadius * 2 + halfBorder,
                contentHeight - halfBorder
            ),
            90f,
            90f,
            false
        )

        // 左侧边框
        borderPath.lineTo(halfBorder, cornerRadius + halfBorder)
        borderPath.arcTo(
            RectF(
                halfBorder,
                halfBorder,
                cornerRadius * 2 + halfBorder,
                cornerRadius * 2 + halfBorder
            ),
            180f,
            90f,
            false
        )

        // 顶部边框
        borderPath.lineTo(contentWidth - cornerRadius - halfBorder, halfBorder)
        borderPath.arcTo(
            RectF(
                contentWidth - cornerRadius * 2 - halfBorder,
                halfBorder,
                contentWidth - halfBorder,
                cornerRadius * 2 + halfBorder
            ),
            -90f,
            90f,
            false
        )

        // 右侧顶部边框
        borderPath.lineTo(triangleLeft - halfBorder, triangleStartY + halfBorder)
        borderPath.lineTo(triangleRight - halfBorder, contentHeight / 2)

        borderPath.close()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        val measuredWidth = measuredWidth
        val measuredHeight = measuredHeight

        val finalWidth = when (trianglePosition) {
            TRIANGLE_POSITION_LEFT, TRIANGLE_POSITION_RIGHT ->
                measuredWidth + triangleHeight.toInt()
            else -> measuredWidth
        }

        val finalHeight = when (trianglePosition) {
            TRIANGLE_POSITION_TOP, TRIANGLE_POSITION_BOTTOM ->
                measuredHeight + triangleHeight.toInt()
            else -> measuredHeight
        }

        setMeasuredDimension(finalWidth, finalHeight)
    }

    override fun setPadding(left: Int, top: Int, right: Int, bottom: Int) {
        super.setPadding(left, top, right, bottom)
        updateContentPadding()
    }

    // 公共方法设置属性
    fun setBubbleColor(color: Int) {
        bubbleColor = color
        bubblePaint.color = color
        invalidate()
    }

    fun setBorderColor(color: Int) {
        borderColor = color
        borderPaint.color = color
        invalidate()
    }

    fun setBorderWidth(width: Float) {
        borderWidth = width
        borderPaint.strokeWidth = width
        invalidate()
    }

    fun setCornerRadius(radius: Float) {
        cornerRadius = radius
        invalidate()
    }

    fun setTriangleSize(width: Float, height: Float) {
        triangleWidth = width
        triangleHeight = height
        updateContentPadding()
        requestLayout()
        invalidate()
    }

    fun setTrianglePosition(position: Int) {
        trianglePosition = position
        updateContentPadding()
        requestLayout()
        invalidate()
    }
}